﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ComponentGo.Web.Schedulers;
using System.IO;
using System.Drawing;
using ComponentGo.Web;

namespace WebSchedulerDemo.xml {
	public partial class Default : System.Web.UI.Page {
		PlanDataSet ds;
		string fileName;

		protected void Page_Load(object sender, EventArgs e) {
			//
			// Reset error information
			//
			ErrorLabel.Text = "";

			//
			// Load from XML file
			//
			ds = new PlanDataSet();
			fileName = MapPath("../App_Data/ProjectsPlanner.xml");
			if (File.Exists(fileName))
				ds.ReadXml(fileName);

			if (!IsPostBack)
				initializeScheduler();
		}

		private void initializeScheduler() {
			Sch.Rows.Clear();

			//
			// Initialize projects' tree
			//
			foreach (PlanDataSet.ProjectsRow rec in ds.Projects) {
				ResourceRow row = createRow(rec);
				if (rec.IsParent_IDNull())
					Sch.Rows.Add(row);
				else {
					ResourceRow parent = Sch.Rows[rec.Parent_ID.ToString()];
					parent.ChildRows.Add(row);
				}
			}

			//
			// Initialize projects' items
			//
			foreach (PlanDataSet.PlanItemRow rec in ds.PlanItem)
				createItem(rec);
		}

		//
		// Menu action handler
		//
		protected void Sch_Action(object sender, ComponentGo.Web.ActionEventArgs e) {
			switch (e.Name) {
				case "rescolor":
					if (Sch.ClickedRow!=null)
						setResourceColor(Sch.ClickedRow, e.Argument);
					break;
				case "new_sub_res":
					if (Sch.ClickedRow!=null)
						addResource(Sch.ClickedRow);
					break;
				case "new_res":
					addResource(null);
					break;
				case "delete_res":
					if (Sch.ClickedRow!=null)
						deleteResource(Sch.ClickedRow);
					break;

				case "itemcolor":
					if (Sch.ClickedItem!=null)
						setItemColor(Sch.ClickedItem, e.Argument);
					break;
				case "new_item":
					if (Sch.ClickedRow!=null && Sch.ClickedDateTime!=DateTime.MinValue)
						addItem(int.Parse(e.Argument));
					break;
				case "delete_item":
					if (Sch.ClickedItem!=null)
						deleteItem();
					break;
				case "item_important":
					if (Sch.ClickedItem!=null) {
						PlanDataSet.PlanItemRow rec = findPlanItem(Sch.ClickedItem);
						rec.Important = !rec.Important;
						Sch.ClickedItem.Row.Items.Remove(Sch.ClickedItem);
						saveItem(createItem(rec));
						Sch.RefreshClientControl();
					}
					break;
				case "item_busy":
					if (Sch.ClickedItem!=null) {
						PlanDataSet.PlanItemRow rec = findPlanItem(Sch.ClickedItem);
						rec.Busy = !rec.Busy;
						Sch.ClickedItem.Row.Items.Remove(Sch.ClickedItem);
						saveItem(createItem(rec));
						Sch.RefreshClientControl();
					}
					break;
			}
		}

		//
		// Method is called by scheduler control when resource row have been changed.
		//
		protected void Sch_RowChanged(object sender, ResourceRowChangedEventArgs e) {
			saveRow(e.Row);
		}

		//
		// Method is called by scheduler control when plan item have been changed.
		//
		protected void Sch_ItemChanged(object sender, SchedulerItemChangedEventArgs e) {
			saveItem(e.Item);
		}

		#region Rows

		private PlanDataSet.ProjectsRow findRow(ResourceRow row) {
			return ds.Projects.FindByProject_ID(int.Parse(row.ResourceID));
		}

		private ResourceRow createRow(PlanDataSet.ProjectsRow rec) {
			ResourceRow row = new ResourceRow(rec.Name, rec.Description);
			row.ResourceID = rec.Project_ID.ToString();
			if (rec.IsParent_IDNull()) {
				row.SumMode = ResourceRowSumMode.AllLevels;
				row.SumText = "Sum items";
				row.SumStyle.BackColor = Color.Yellow;
				row.SumStyle.HorizontalAlign = HorizontalAlign.Center;
			}
			if (!rec.IsColorNull()) {
				row.BodyStyle.BackColor = ColorTranslator.FromHtml(rec.Color);
				row.HeaderStyle.BackColor = ColorTranslator.FromHtml(rec.Color);
			}
			row.Expanded = rec.Expanded;

			return row;
		}

		private void saveRow(ResourceRow resourceRow) {
			//
			// Save project record back to database
			//
			PlanDataSet.ProjectsRow row = findRow(resourceRow);
			if (row!=null) {
				row.Name = resourceRow.Texts[0];
				row.Description = resourceRow.Texts[1];
				if (resourceRow.BodyStyle.BackColor.IsEmpty)
					row.SetColorNull();
				else
					row.Color = ColorTranslator.ToHtml(resourceRow.BodyStyle.BackColor);
				row.Expanded = resourceRow.Expanded;
			}
			ds.WriteXml(fileName);
			Sch.RefreshClientControl();
		}

		private void setResourceColor(ResourceRow resourceRow, string colorName) {
			resourceRow.BodyStyle.BackColor = ColorTranslator.FromHtml(colorName);
			resourceRow.HeaderStyle.BackColor = ColorTranslator.FromHtml(colorName);
			saveRow(resourceRow);
		}

		private void deleteResource(ResourceRow row) {
			PlanDataSet.ProjectsRow rec = findRow(row);
			if (rec.GetProjectsRows().Length>0)
				ErrorLabel.Text = "You can not delete resource row with a children rows.";
			else {
				rec.Delete();
				saveRow(row);

				if (row.Parent!=null)
					row.Parent.ChildRows.Remove(row);
				else
					Sch.Rows.Remove(row);
			}
		}

		private void addResource(ResourceRow parent) {
			PlanDataSet.ProjectsRow rec = ds.Projects.NewProjectsRow();
			rec.Name = "New project";
			rec.Description = "";
			rec.Expanded = true;
			if (parent!=null)
				rec.Parent_ID = findRow(parent).Project_ID;
			ds.Projects.AddProjectsRow(rec);

			ResourceRow row = createRow(rec);
			if (parent!=null)
				parent.ChildRows.Add(row);
			else
				Sch.Rows.Add(row);
			saveRow(row);
			row.ResourceID = rec.Project_ID.ToString();
		}

		#endregion

		#region Plan items

		private PlanDataSet.PlanItemRow findPlanItem(SchedulerItem it) {
			return ds.PlanItem.FindByPlanItem_ID(int.Parse(it.ItemID));
		}

		private SchedulerItem createItem(PlanDataSet.PlanItemRow rec) {
			SchedulerItem it = new SchedulerItem();
			it.Text = rec.Name;
			it.DateBegin = rec.DateBegin;
			it.DateEnd = rec.DateEnd;
			it.ItemID = rec.PlanItem_ID.ToString();

			if (!rec.IsColorNull())
				it.Style.BackColor = ColorTranslator.FromHtml(rec.Color);

			if (rec.Busy)
				it.DisplayText = "<img src=../images/busy.gif> |";
			if (rec.Important) {
				if (!string.IsNullOrEmpty(it.DisplayText))
					it.DisplayText = "<img src=../images/important.gif>"+it.DisplayText;
				else
					it.DisplayText = "<img src=../images/important.gif> |";
			}
			it.Tooltip = it.DateBegin+"..."+it.DateEnd;

			Sch.Rows[rec.Project_ID.ToString()].Items.Add(it);

			return it;
		}

		private void saveItem(SchedulerItem schedulerItem) {
			//
			// Save plan item record back to database
			//
			PlanDataSet.PlanItemRow row = findPlanItem(schedulerItem);
			if (row!=null) {
				row.Name = schedulerItem.Text;
				row.DateBegin = schedulerItem.DateBegin;
				row.DateEnd = schedulerItem.DateEnd;
				row.Project_ID = int.Parse(schedulerItem.Row.ResourceID);
				if (schedulerItem.Style.BackColor.IsEmpty)
					row.SetColorNull();
				else
					row.Color = ColorTranslator.ToHtml(schedulerItem.Style.BackColor);
			}
			ds.WriteXml(fileName);
			Sch.RefreshClientControl();
		}

		private void setItemColor(SchedulerItem it, string colorName) {
			it.Style.BackColor = ColorTranslator.FromHtml(colorName);
			saveItem(it);
		}

		private void addItem(int nDays) {
			PlanDataSet.PlanItemRow rec = ds.PlanItem.NewPlanItemRow();
			rec.Name = "New item";
			rec.Project_ID = int.Parse(Sch.ClickedRow.ResourceID);
			rec.DateBegin = Sch.ClickedDateTime;
			rec.DateEnd = Sch.ClickedDateTime.AddDays(nDays);
			rec.Busy = false;
			rec.Important = false;
			ds.PlanItem.AddPlanItemRow(rec);

			SchedulerItem it = createItem(rec);
			saveItem(it);

			it.ItemID = rec.PlanItem_ID.ToString();
		}

		private void deleteItem() {
			findPlanItem(Sch.ClickedItem).Delete();
			saveItem(Sch.ClickedItem);

			Sch.ClickedItem.Row.Items.Remove(Sch.ClickedItem);
		}

		#endregion

		protected void DefaultDataLink_Click(object sender, EventArgs e) {
			//
			// Restore resources and items from default xml file.
			//
			string defaultsFileName = MapPath("../App_Data/DefaultsProjectsPlanner.xml");
			ds.Clear();
			ds.ReadXml(defaultsFileName);
			ds.WriteXml(fileName);

			//
			// Reinitialize scheduler control with new rows.
			//
			Sch.Rows.Clear();
			initializeScheduler();
		}

		//
		// Called when java script code is prepared on scheduler control callback.
		//
		protected void Sch_CallbackScript(object sender, ComponentGo.Web.CallbackScriptEventArgs e) {
			e.ClientScript.AppendFormat("document.getElementById({0}).innerHTML = {1};",
				JScriptTools.QuoteString(ErrorLabel.ClientID), JScriptTools.QuoteString(ErrorLabel.Text));
		}
	}
}
